package com.sfhk.web;

import com.sfhk.domain.User;
import com.sfhk.service.UserService;
import com.sfhk.service.impl.UserServiceImpl;
import com.sfhk.utils.LoginException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.接收请求
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String check = request.getParameter("verifycode");
        Object cWord = request.getSession().getAttribute("checkcode_session");
        System.out.println("1:"+check+"2:"+cWord);
        // 2.调用service的方法
        if (check.equals(cWord)) {
            try {
                User loginuser = userService.login(username, password);
                request.getSession().setAttribute("loginuser", loginuser);
                response.sendRedirect(request.getContextPath());
                System.out.println(request.getContextPath());
            } catch (LoginException e) {
                request.setAttribute("errorMessage", e.getMessage());
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
            // 3.request域传递数据

            // 4.转发到jsp中
        }else {
            request.setAttribute("errorMessage", "验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
